package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 帖子用户层实现类
 * User: DELL
 * Date: 2023-09-21
 * Time: 22:51
 */

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;
    // 引入用户和板块的 service,此处一定要注意不能形成循环依赖
    // 即在用户和板块的 service层中均不能依赖注入帖子的 service
    @Resource
    private IBoardService boardService;
    @Resource
    private IUserService userService;

    @Override
    public void create(Article article) {
        // 1.非空校验
        if (article == null || article.getUserId() == null || article.getBoardId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 2.处理默认值
        article.setVisitCount(0);
        article.setLikeCount(0);
        article.setReplyCount(0);
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        // 3.新增帖子到数据库
        int row = articleMapper.insertSelective(article);
        // 4.检验受影响的行数
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_CREATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }
        // 5.增加对应用户的帖子数
        userService.addOneArticleCountById(article.getUserId());
        // 6.增加对应板块的帖子数
        boardService.addOneArticleCountById(article.getBoardId());
        // 7.打印日志
        log.info(ResultCode.SUCCESS_BOARD_CREATE.toString() + "article id = " + article.getId());
    }

    @Override
    public List<Article> selectAll() {
        // 调用 dao 并返回结果
        return articleMapper.selectAll();
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 参数校验
        if (boardId == null || boardId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验板块是否存在
        Board board = boardService.selectById(boardId);
        if (board == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 调用 dao,查询并返回结果
        return articleMapper.selectAllByBoardId(boardId);
    }

    @Override
    public List<Article> selectAllByUserId(Long userId) {
        // 参数校验
        if (userId == null || userId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询数据库并返回结果
        return articleMapper.selectAllByUserId(userId);
    }

    @Override
    public Article selectById(Long id) {
        // 参数校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询数据库并返回
        return articleMapper.selectByPrimaryKey(id);
    }

    @Override
    public Article getDetailById(Long id) {
        // 参数校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 查询用户信息
        User user = userService.selectById(article.getUserId());
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 查询板块信息
        Board board = boardService.selectById(article.getBoardId());
        if (board == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 组装数据
        article.setUser(user);
        article.setBoard(board);
        // 返回结果
        return article;
    }

    @Override
    public void updateVisitCount(Long id) {
        // 参数校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        articleMapper.updateVisitCount(id);
        // 因为 visitCount 不追求准确值,只有大概值即可,因此不进行检验
    }

    @Override
    public void modify(Long id, String title, String content) {
        // 参数校验
        if (id == null || id <= 0 || StringUtil.isEmpty(title)
                || StringUtil.isEmpty(content)) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 构造 article 对象
        Article article = new Article();
        article.setId(id);
        article.setTitle(title);
        article.setContent(content);
        Date date = new Date();
        article.setUpdateTime(date);
        // 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(article);
        // 校验参数
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_UPDATE.toString() + "article id = " + id + ", 受影响的行数 row =  " + row);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_UPDATE));
        }
    }

    @Override
    public void updateLikeCount(Long id) {
        // 参数校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        articleMapper.updateLikeCount(id);
        // 因为 likeCount 不追求准确值,只有大概值即可,因此不进行检验
    }

    @Override
    public void deleteById(Long id) {
        // 参数校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 根据id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        // 校验帖子信息
        if (article == null || article.getDeleteState() != 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 重新构造 article 对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        // 更新帖子的 deleteState
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_UPDATE.toString() + "article id = " + id + ", 受影响的行数 row =  " + row);
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_UPDATE));
        }
        // 将对应用户表中的帖子数减一
        userService.delOneArticleCountById(article.getUserId());
        // 将对应板块表中的帖子数减一
        boardService.delOneArticleCountById(article.getBoardId());
        // 打印日志
        log.info("删除帖⼦成功, article id = " + article.getId());
    }
}
